﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.IO;
using System.Linq;
using DNA.IO.Compress;
using DNA.Utility;

namespace DNA.Mvc.Data.Xml
{
    public class PackageZipXmlRepository : PackageXmlRepository
    {
        public PackageZipXmlRepository(string searchPath) : base(searchPath) { }

        protected override void PreLoadPackages()
        {
            var subPaths = Directory.GetDirectories(storagePath);
            foreach (var dir in subPaths)
            {
                var fs = Directory.GetFiles(dir, "*.zip");
                if (fs.Length > 0)
                {
                    try
                    {
                        foreach (var f in fs)
                        {
                            using (var zip = new ZipExtract(f))
                            {
                                var files = zip.ReadFiles();
                                var manifest = files.FirstOrDefault(zf => zf.EndsWith("manifest.xml", StringComparison.OrdinalIgnoreCase));
                                if (!string.IsNullOrEmpty(manifest))
                                {
                                    var xml = zip.ReadFileAsText(manifest);
                                    var descriptor = XmlSerializerUtility.DeserializeFromXmlText<PackageDescriptor>(xml);
                                    var pkg = PackageConverter.Convert(descriptor);
                                    pkg.Url = fs[0];
                                    Dbset.Add(pkg);
                                }
                            }
                        }
                    }
                    catch(Exception e)
                    {
                        continue;
                    }
                }
            }
        }
    }
}
